# -*- coding:utf-8 -*-

"""
JOAQUÍN RAMÓN ANTÚNEZ SÁNCHEZ - 11 de septiembre de 2014
"""

import MySQLdb as db

class monconst:
    MYSQL_CONEXION  = ['localhost', 'root', '2629buruaz', 'amadeus']
    MYSQL_SET_NAMES = 'SET NAMES "utf8"'

class monstr(str):

    def toupper(self):
        return self.decode('utf-8').upper().strip()
    
    def tolower(self):
        return self.decode('utf-8').lower().strip()
    
    def totitle(self):
        return self.decode('utf-8').title().strip()
    
    def tocapitalize(self):
        return self.decode('utf-8').strip().captitalize()
    
'''monsql - establecer conexión y consultas con la db Amadeus'''
class monsql:
    
    def __init__(self):
        self.con = db.connect(*monconst.MYSQL_CONEXION)
        self.con.query( monconst.MYSQL_SET_NAMES )
    
    def __del__(self):
        self.con.close()
        self.con = None    
        
    
    def execute(self, query):
        cursor = self.con.cursor( db.cursors.DictCursor )
        result = None
        try:
            cursor.execute( query )
            if str(query).lower().startswith('select'):
                result = cursor.fetchone()
            else:
                self.con.commit()
                result = cursor.rowcount
            
        except Exception as ex:
            print ex.message
        finally:
            cursor.close()
            cursor = None  
        
        return result
    
    def inc(self, tabla, condicion = None):
        query = 'select max(id) as id from {}'.format( tabla )
        if condicion:
            query = '{}\nwhere {}'.format(query, condicion)
            
        x = self.execute(query)
        if not x['id']:
            return 1
        else:
            return 1 + int(x['id'])    
        
    # propiedades
    def __get_cursor(self): return self.con.cursor(db.cursors.DictCursor)
    
    cursor = property(__get_cursor)
    
'''
Clase "singleton" alternativa a monsql
'''    

    
class jr:
    
    __instance  = None
    __con       = None            
    
    @staticmethod
    def instance():
        if not jr.__instance:
            jr.__instance = jr()
            jr.__con = db.connect('localhost', 'root', '2629buruaz')
            jr.__con.query("SET NAMES 'utf8'")
        
        return jr.__instance
    
    def execute(self, query):
        cursor = None
        result = None
        try:
            cursor = jr.__con.cursor(db.cursors.DictCursor)
            cursor.execute(query)
            if str(query).lower().startswith('select '):
                result = cursor.fetchall()
            else:
                jr.__con.commit()
                result = cursor.rowcount
        except Exception as e:
            print e.message
        finally: 
            if cursor:
                cursor.close()
                cursor = None
        
        return result
    
    def inc(self, tabla, condicion = None):
        query = 'select max(id) as id from %s' % (tabla)
        if condicion:
            query += '\nwhere %s' % (condicion)
        row = self.execute(query)
        if row and len(row) == 1 and row[0]['id']:
            return int(row[0]['id']) + 1
        else:
            return 1
        
    def size(self, tabla, campo):
        query = 'show columns from %s like "%s"' % ( tabla, str(campo).lower() )
        cursor = jr.__con.cursor(db.cursors.DictCursor)
        cursor.execute(query)
        row = cursor.fetchall()
        cursor.close()
        cursor = None
        
        if row and row[0]['Type']:
            x1 = str(row[0]['Type']).find('(')
            x2 = str(row[0]['Type']).find(')')
            if x1 != -1 and x2 != -1:
                s = str( row[0]['Type'])[x1 + 1 : x2]
                if s.isdigit(): return int(s)
                else: return 0
            else:
                return 0            
        else:
            return 0                          
        
    
    def close(self):
        if jr.__con:
            jr.__con.close()
            jr.__con = None   